/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.servlet;

import com.dao.AccountDAO;
import com.dao.PostDAO;
import com.entities.Account;
import com.entities.PostType;
import com.entities.Posts;
import com.utilities.XMLUtilities;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 *
 * @author Min Tun
 */
public class Controller extends HttpServlet {

    private static final String homePage = "index.jsp";
    private static final String loginPage = "login.html";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        //PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("btAction");
            if (action == null) {
                PostDAO dao = new PostDAO();
                Posts posts = dao.loadDataToXML();
                request.setAttribute("POSTS", posts);
                RequestDispatcher rd = request.getRequestDispatcher(homePage);
                rd.forward(request, response);
            } else if (action.equals("login")) {
                String username = request.getParameter("txtUsername");
                String password = request.getParameter("txtPassword");
                AccountDAO dao = new AccountDAO();
                Account result = dao.checkLogin(username, password);
                if (result != null) {
                    System.out.println(result.getAccount());
                    HttpSession session = request.getSession();
                    session.setAttribute("ACC", result);
                    response.sendRedirect(homePage);
                } else {
                    request.setAttribute("ERR", "Tài khoản hoặc mật khẩu không chính xác!");
                    RequestDispatcher rd = request.getRequestDispatcher(loginPage);
                    rd.forward(request, response);
                }

            } else if (action.equals("logout")) {
                HttpSession session = request.getSession(false);
                session.setAttribute("ACC", null);
                response.sendRedirect(homePage);
            } else if (action.equals("BaoKim.Vn")) {
                int amount = Integer.parseInt(request.getParameter("amount"));
                String receiver = "locmxse60602@gmail.com";
                String postID = request.getParameter("pID");
                String name = "Ung ho hoan canh kho khan.";
                String url = "https://www.baokim.vn/payment/product/version11?business="
                        + receiver + "&product_name=" + name + "&url_success="
                        + "http://localhost:8084?btAction=gotDonate&pID=" + postID
                        + "&product_price=" + amount + "&product_quantity=1&total_amount="
                        + amount;
                response.sendRedirect(url);

            } else if (action.equals("NganLuong.Vn")) {
                int amount = Integer.parseInt(request.getParameter("amount"));
                String receiver = "locmxse60602@gmail.com";
                String postID = request.getParameter("pID");
                String name = "Ung ho hoan canh kho khan.";
                String url = "https://www.nganluong.vn/button_payment.php?receiver="
                        + receiver + "&product_name=" + name + "&return_url="
                        + "http://localhost:8084?btAction=gotDonate&pID=" + postID
                        + "&price=" + amount;
                response.sendRedirect(url);
            } else if (action.equals("post")) {
                Date date = new Date();
                long tmp = date.getTime();
                String id = String.valueOf(tmp).substring(0, 9);
                String title = request.getParameter("txtTitle");
                String description = request.getParameter("txtDescription");
                String priority = request.getParameter("txtPriority");
                System.out.println(priority);
                String address = request.getParameter("txtAddress");

                PostType p = new PostType();
                p.setAddress(address);
                p.setDescription(description);
                p.setId(id);
                p.setMember("locmxse60602");
                p.setPostedDate(new Date());
                p.setPriorityID(Integer.parseInt(priority));
                p.setTitle(title);

//                PostDAO dao = new PostDAO();
//                int result = dao.insertPost(p);
                String xmlPath = getServletContext().getRealPath("/") + "WEB-INF/posts.xml";
                XMLUtilities.writePostXMLFile(p, xmlPath);
            } else if (action.equals("loadXML")) {
                response.setContentType("text/xml");
                PostDAO dao = new PostDAO();
                try {
                    JAXBContext jaxbc = JAXBContext.newInstance(Posts.class);
                    Posts posts = dao.loadDataToXML();

                    Marshaller m = jaxbc.createMarshaller();
                    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
                    m.marshal(posts, response.getOutputStream());
                } catch (JAXBException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } finally {
            //out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
